# -*- coding: utf-8 -*-
from pycube.core.urls.response import HttpResponse
from mod_list import list
from urlparse import urlparse
import logging
from privat.admin import *
from models import auth
'''
Created on 24.09.2009

@author: varg
'''
def url_parse( url ):
    return url.split( '/' )
def pipe_url( *arg ):
    return "%s" % '/'.join( arg )


def __init__( req, tpl ):
    start( req, tpl )
    checkauth( req, tpl )
    return


@not_auth
def checkauth( req, tpl ):
    ca = auth( req.psql )
    if req.post:
        if ca.check_auth( req.post['login'], req.post['password'], req.session['SID'] ):
            return HttpResponse.map( redirect="/core/" )
    tpl.push( 'auth.html', 'document' )
    tpl.tag( 'title', "админ" )
    return
@auth_only
def start( req, tpl ):
    tpl.push( '__admin__.admincontent', 'document', {'admin_name':req.session['user_login']} )
    menu, subm = list()
    #настройка урлов
    u = "%s://%s%s" % ( req.environ['wsgi.url_scheme'], req.environ['HTTP_HOST'], req.environ['REQUEST_URI'] )
    uri = urlparse( u )
    root_url = url_parse( uri[2] )
    url_to_parse = "%s://%s" % ( uri[0], uri[1] )
    url_to_parse = pipe_url( url_to_parse, root_url[1] )
    #req.write( pipe_url( url_to_parse, uri[0], uri[1] ) )
    url_map = []
    for m in menu:
        mod = ''
        if req.access( m['permission'] ):
            tpl.parse( 'menu', {'menu_cat':m['name']} )
            if 'mod' in m:mod = '%s.%s' % ( m['mod'], '__init__' )
            for s in subm[m['permission']]:
                if req.access( s['permission'] ):
                    if 'mod' in s:mod = '%s.%s' % ( s['mod'], '__init__' )
                    url_map.append( [pipe_url( m['url'], s['url'] ), mod] )
                    tpl.parse( 'menu_item', {'menu_name':s['name'], 'menu_link':pipe_url( url_to_parse, m['url'], s['url'] )} )
    url_pattern = ( ['^/core/user/settings$', 'users.__init__'], ['^/core/user/permission$', asd] )#tuple( url_map )
    req.write( url_pattern )
    return HttpResponse.map( urls=url_pattern )
def qwe():
def asd( req, tpl ):
    req.write( 'sdfsdf' )
